package com.tanchengjin.admin.controller;

import com.tanchengjin.admin.model.dao.AdminPermissionMenuMapper;
import com.tanchengjin.admin.model.pojo.AdminMenu;
import com.tanchengjin.admin.model.pojo.AdminPermission;
import com.tanchengjin.admin.model.pojo.AdminPermissionMenu;
import com.tanchengjin.admin.model.vo.LayuiTreeVO;
import com.tanchengjin.admin.service.AdminMenuService;
import com.tanchengjin.admin.service.AdminPermissionService;
import com.tanchengjin.admin.service.AdministratorService;
import com.tanchengjin.admin.service.impl.AdminMenuServiceImpl;
import com.tanchengjin.admin.utils.LayuiAdminServerResponse;
import com.tanchengjin.admin.utils.ServerResponse;
import org.hibernate.validator.HibernateValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import org.springframework.validation.beanvalidation.SpringValidatorAdapter;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

/**
 * @author tanchengjin
 */
@Controller
@Validated
@RequestMapping("${app.admin.prefix}/administrators/menu")
@Deprecated
public class AdminMenuController {
    /**
     * service
     */
    @Autowired
    private AdminMenuService adminMenuService;

    @Autowired
    private AdministratorService administratorService;

    @Autowired
    private AdminPermissionService adminPermissionService;

    @Autowired
    private AdminPermissionMenuMapper adminPermissionMenuMapper;

    @GetMapping("/index")
    public String index(Model model) {
        //List<AdminMenu> adminMenuList = adminMenuService.getAll();
        //左侧分类树
        model.addAttribute("adminMenuList", adminMenuService.getNodeTree());
        List<AdminMenu> directoryList = adminMenuService.getNodeTree();
        //右侧分类列表
        model.addAttribute("adminMenuListDirectory", directoryList);


        //获取所有权限
        List<AdminPermission> permissionList = adminPermissionService.getAll();
        model.addAttribute("permissionList", permissionList);

        return "/admin/administrators/menu/list";
    }

    @RequestMapping(value = "/list", method = {RequestMethod.GET})
    @ResponseBody
    public LayuiAdminServerResponse index() {
        List<AdminMenu> adminMenuList = adminMenuService.getSimpleNodeTree();
        long count = adminMenuService.count();
        return LayuiAdminServerResponse.responseWithSuccess(adminMenuList, String.valueOf(count));
    }

    @RequestMapping(value = "/tree", method = {RequestMethod.GET})
    public String tree(Model model) {
        //左侧分类树
        model.addAttribute("adminMenuList", adminMenuService.getNodeTree());
        List<AdminMenu> directoryList = adminMenuService.getNodeTree();
        //右侧分类列表
        model.addAttribute("adminMenuListDirectory", directoryList);
        //获取所有权限
        List<AdminPermission> permissionList = administratorService.getAdminPermissionList();
        model.addAttribute("permissionList", permissionList);
        return "/admin/administrators/menu/tree";
    }

    @RequestMapping(value = "/create", method = {RequestMethod.GET})
    public String create(Model view) {
        //获取所有权限
        List<AdminPermission> permissionList = adminPermissionService.getAll();
        view.addAttribute("permissionList", permissionList);
        //下拉框菜单选项
        List<AdminMenu> directoryList = adminMenuService.getNodeTree();
        view.addAttribute("adminMenuListDirectory", directoryList);
        return "/admin/administrators/menu/add";
    }

    @RequestMapping(value = "", method = {RequestMethod.POST})
    @ResponseBody
    public ServerResponse store(AdminMenu adminMenu) {
        int i = adminMenuService.insert(adminMenu);
        if (i >= 1) {
            return ServerResponse.responseWithSuccess();
        } else {
            return ServerResponse.responseWithFailureMessage("创建失败请重试");
        }
    }

    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    @ResponseBody
    public ServerResponse<AdminMenu> show(@PathVariable("id") int id) {
        AdminMenu adminMenu = adminMenuService.findById(id);
        return ServerResponse.responseWithSuccess(adminMenu);
    }

    @RequestMapping(value = "/{id}/edit", method = {RequestMethod.GET})
    public String edit(Model view, @PathVariable(value = "id") int id) {
        AdminMenu adminMenu = adminMenuService.findById(id);
        view.addAttribute("adminMenu", adminMenu);


        //获取所有权限
        List<AdminPermission> permissionList = adminPermissionService.getAll();
        view.addAttribute("permissionList", permissionList);

        //获取当前菜单已保存的权限
        List<AdminPermissionMenu> adminPermissionMenus = adminPermissionMenuMapper.selectByMenuId(id);
        ArrayList<Integer> currentMenuPermissions = new ArrayList<>();
        for (AdminPermissionMenu adminPermissionMenu : adminPermissionMenus) {
            currentMenuPermissions.add(adminPermissionMenu.getAdminPermissionId());
        }
        view.addAttribute("currentMenuPermissions", currentMenuPermissions);

        List<AdminMenu> directoryList = adminMenuService.getNodeTree();
        //右侧分类列表
        view.addAttribute("adminMenuListDirectory", directoryList);

        return "/admin/administrators/menu/edit";
    }

    @RequestMapping(value = "/{id}", method = {RequestMethod.PUT})
    @ResponseBody
    public ServerResponse update(AdminMenu adminMenu, @PathVariable("id") int id) {
        int i = adminMenuService.updateById(adminMenu, id);
        if (i >= 1) {
            return ServerResponse.responseWithSuccess();
        } else {
            return ServerResponse.responseWithFailureMessage("更新失败，请重试");
        }
    }

    @RequestMapping(value = "/{id}", method = {RequestMethod.DELETE})
    @ResponseBody
    public ServerResponse destroy(@PathVariable(value = "id") int id) {
        int i = adminMenuService.deleteById(id);

        if (i >= 1) {
            return ServerResponse.responseWithSuccess();
        } else {
            return ServerResponse.responseWithFailureMessage("删除失败请重试");
        }
    }

    //获取所有的目录分类
    @RequestMapping(value = "/directory", method = {RequestMethod.GET})
    @ResponseBody
    public ServerResponse directoryList() {
        List<AdminMenu> directoryList = adminMenuService.getNodeTree();
        return ServerResponse.responseWithSuccess(directoryList);
    }

    //排序操作
    @RequestMapping(value = "/sortOperator", method = {RequestMethod.PUT})
    @ResponseBody
    public ServerResponse sortOperator(@RequestParam("id") int id, @RequestParam("target_id") int target_id, @RequestParam(value = "node_id", required = false) Integer parent_id) {

        if (parent_id == null || parent_id == 0) parent_id = null;
//        if ((target_id == 0) && (parent_id == null || parent_id == 0)) {
//            return ServerResponse.responseWithFailureMessage("节点ID与目标ID不能同时为空");
//        }
        int i = adminMenuService.updateSort2(id, AdminMenuServiceImpl.SortDirection.BEFORE, target_id, parent_id);
        if (i >= 1) {
            return ServerResponse.responseWithSuccess();
        } else {
            return ServerResponse.responseWithFailure();
        }
    }

    /**
     * 获取某角色的权限树
     *
     * @param roleId 角色id
     * @return 权限树
     */
    @RequestMapping(value = "/treeNode", method = {RequestMethod.GET})
    @ResponseBody
    public ServerResponse menuTree(@RequestParam(value = "role_id", required = false) @NotNull(message = "角色不允许为空") Integer roleId) {
        List<AdminMenu> all = adminMenuService.getNodeTree();
        return ServerResponse.responseWithSuccess(buildLayuiTree(all, roleId));
    }

    /**
     * 构建layui前端节点树
     */
    private List<LayuiTreeVO> buildLayuiTree(List<AdminMenu> adminMenus, Integer roleId) {
        ArrayList<LayuiTreeVO> layuiTreeVOS = new ArrayList<>();

        if (adminMenus.size() >= 1) {
            for (AdminMenu adminMenu : adminMenus) {
                LayuiTreeVO layuiTreeVO = new LayuiTreeVO();
                layuiTreeVO.setTitle(adminMenu.getName());
                layuiTreeVO.setId(adminMenu.getId());
                layuiTreeVO.setChecked(adminMenuService.checkRoleHasPermission(roleId, adminMenu.getId()));
                if (adminMenu.getChildren() != null && adminMenu.getChildren().size() >= 1) {
                    List<LayuiTreeVO> layuiTreeVOS1 = this.buildLayuiTree(adminMenu.getChildren(), roleId);
                    layuiTreeVO.setChildren(layuiTreeVOS1);
                }
                layuiTreeVOS.add(layuiTreeVO);
            }
        }
        return layuiTreeVOS;
    }
}
